package org.shop.controller.app;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.hmef.Attachment;
import org.shop.entity.Merchant;
import org.shop.entity.Users;
import org.shop.entity.security.MyUserDetail;
import org.shop.service.AttentionService;
import org.shop.service.GoodsService;
import org.shop.service.MerchantService;
import org.shop.service.OrdersService;
import org.shop.service.UserService;
import org.shop.util.CommonUtil;
import org.shop.util.DateUtils;
import org.shop.util.FtpUtil2;
import org.shop.util.MD5Util;
import org.shop.util.ObjUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import net.coobird.thumbnailator.Thumbnails;

@Controller
public class UserController {
	
	private static Logger logger = LogManager.getLogger(UserController.class);
	
	@Autowired
    private UserService userService;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private OrdersService ordersService;
	@Autowired
	private AttentionService attentionService;
	@Autowired
	private MerchantService merchantService;
	
	/**
	 * 商家注册
	 * @param req
	 * @return
	 */
	@RequestMapping("userRegister")
	@ResponseBody
	public Map<String, Object> userRegister(HttpServletRequest req){
		Map<String, Object> map = new HashMap<String, Object>();
		String userName = req.getParameter("userName");
		String phone = req.getParameter("phone");
		String password = req.getParameter("password");
		String volatileCode = req.getParameter("volatileCode");
		String schoolId = req.getParameter("schoolId");
		try {
			HttpSession session=req.getSession(false);
			Integer tempVolatileCode=(Integer) session.getAttribute(phone);
			
			Users users=userService.findUserByLoginName(phone);
			if(users!=null){
				map.put("state", -2);
	            map.put("msg", "手机号已经存在");
	            return map;
			}
			if(volatileCode.equals(tempVolatileCode+"")){
				Users user = new Users();
				user.setUserName(userName);
				user.setLoginName(phone);
				user.setPhone(phone);
				user.setPassword(MD5Util.MD5(password));
				user.setSchoolId(Long.parseLong(schoolId));
				user.setUserType((long) 1);
				userService.insertSelective(user);
				map.put("state", 1);
	            map.put("msg", "注册成功");
			}else{
				map.put("state", -1);
	            map.put("msg", "验证码不正确");
			}
		} catch(Exception e) {
			e.printStackTrace();
			logger.error(e);
			map.put("state", 0);
            map.put("msg", "注册失败");
		}
		
		return map;
	}
	/**
	 * 获取登录人信息
	 * @param req
	 * @return
	 */
	@RequestMapping("app/getUser")
	@ResponseBody
	public Users getUser(HttpServletRequest req){
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		Users user = null;
		try {
			user = userService.selectByPrimaryKey(ud.getUserId());
		} catch(Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		
		return user;
	}
	/** 
	* @Title: toPersonCenter 
	* @Description: TODO(跳转个人中心) 
	* @param @param req
	* @param @return     
	* @return String    返回类型 
	* @throws 
	*/
	@RequestMapping("app/toPersonCenter")
	public String toPersonCenter(HttpServletRequest req){
		Map<String,Object> paramMapFocus = new HashMap<String,Object>();
		Map<String,Object> paramMapFans = new HashMap<String,Object>();
		try{
			MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			paramMapFans.put("targetId", ud.getUserId());
			paramMapFans.put("attentionType", 0);
			int fansCount = attentionService.getMyFocusAndFansCount(paramMapFans);
			paramMapFocus.put("userId", ud.getUserId());
			paramMapFocus.put("attentionType", 0);
			int focusCount = attentionService.getMyFocusAndFansCount(paramMapFocus);
			Users users1 = userService.selectByPrimaryKey(ud.getUserId());
			int orderCount = ordersService.getUsersOfOrderCount(ud.getUserId());
			Merchant merchant = null;
			if(ObjUtil.isNotNullAndEmpty(users1.getMerchantId())) {
				merchant = merchantService.selectByPrimaryKey(users1.getMerchantId());
			}
			req.setAttribute("users", users1);
			req.setAttribute("fansCount", fansCount);
			req.setAttribute("focusCount", focusCount);
			req.setAttribute("orderCount", orderCount);
			req.setAttribute("merchant", merchant);
		}catch(Exception e){
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return "app/personCenter";
	}
	/**
	 * 获取所有用户信息
	 * @param req
	 * @return
	 */
	@RequestMapping("app/getUsersList")
	@ResponseBody
	public List<Users> getUsersList(HttpServletRequest req){
		List<Users> list = userService.getUsersList();
		return list;
	}

	/** 
	* @Title: toMyProfile 
	* @Description: TODO(根据传来的用户id展示个人信息) 
	* @param @param req
	* @param @return     
	* @return String    返回类型 
	* @throws 
	*/
	@RequestMapping("app/toMyProfile")
	public String toMyProfile(HttpServletRequest req){
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		try{
			Users users = userService.selectByPrimaryKey(ud.getUserId());
			req.setAttribute("users", users);
			if(users.getIdNo()!=null) {
				req.setAttribute("birthday", (users.getIdNo().substring(6, 10)+"-"+users.getIdNo().substring(10, 12)+"-"+users.getIdNo().substring(12, 14)));
			}else{
				req.setAttribute("birthday","");
			}
		}catch(Exception e){
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return "app/myProfile";
	}
	
	/** 
	* @Title: updMyProfile 
	* @Description: TODO(修改用户信息) 
	* @param @param req
	* @param @return     
	* @return int    返回类型 
	* @throws 
	*/
	@RequestMapping("app/updMyProfile")
	@ResponseBody
	public int updMyProfile(HttpServletRequest req){
		int num = 0;
		try{
			Users users = new Users();
			MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			Users users1 = userService.selectByPrimaryKey(ud.getUserId());
			String sex = req.getParameter("sexValue");
			if(users1.getUserSex()==sex&&sex!=null){
				num = 2;
			}else{
				users.setUserId(ud.getUserId());
				String userName = req.getParameter("userName");
				if(userName!=null&&userName!=""){
					users.setUserName(userName);
				}
				if(sex!=null&&sex!=""){
					users.setUserSex(sex);
				}
				String phone = req.getParameter("phone");
				if(phone!=null&&phone!=""){
					users.setPhone(phone);
				}
				num = userService.updateByPrimaryKeySelective(users);
			}
		}catch(Exception e){
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return num;
	}
	
	
	/**
	 * 上传个人头像
	 * @param req
	 * @return
	 */
	@RequestMapping("app/uploadHeadImg")
	@ResponseBody
	public Map<String, Object> uploadUsedImg(HttpServletRequest req){
		Map<String, Object> map=new HashMap<String, Object>();
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    	String photoStr="";
    	String mainPhotoStr="";
		FTPClient ftpClient =null;
		InputStream is = null;
		try{
    		//创建一个通用的多部分解析器
    		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(req.getSession().getServletContext());
    		//转换成多部分request  
    		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)req;
    		//判断 request 是否有文件上传,即多部分请求
    		if(multipartResolver.isMultipart(req)){
    			//取得request中的所有文件名
    			Iterator<String> iter = multiRequest.getFileNames();
    			//创建ftp链接
    			String ftp_photoDirectory="shop/image/" + DateUtils.toYmdX(new Date());
    			ftpClient=FtpUtil2.connect(CommonUtil.getPropertiesParam("ftp_address"), Integer.parseInt(CommonUtil.getPropertiesParam("ftp_port")), CommonUtil.getPropertiesParam("ftp_user"), CommonUtil.getPropertiesParam("ftp_password"), ftp_photoDirectory);
    			while(iter.hasNext()){
    				String name=iter.next();
    				if(name.equals("goodsMainPhoto")){
    					//取得上传文件
        				List<MultipartFile> fileList = multiRequest.getFiles(name);
        				if(fileList!=null){
        					for(MultipartFile file:fileList){
        						if(file != null){
        							//取得当前上传文件的文件名称
        	    					String myFileName = file.getOriginalFilename();
        	    					myFileName=FtpUtil2.generateFileName(myFileName);
        	    					//如果名称不为"",说明该文件存在，否则说明该文件不存在
        	    					if(myFileName.trim() !=""){
        	    						myFileName=FtpUtil2.generateFileName(myFileName);
        	    						//按照比例进行缩小和放大
                                        ByteArrayOutputStream bos=new ByteArrayOutputStream();
                                        Thumbnails.of(file.getInputStream()).scale(0.2f).toOutputStream(bos);
                                        is = new ByteArrayInputStream(bos.toByteArray());
                                        
        	    						FtpUtil2.upload(myFileName, is, ftpClient);
        	    						mainPhotoStr+=ftp_photoDirectory+"/"+myFileName;
        	    					}
        						}
        					}
        				}
    				}else{
    					//取得上传文件
        				List<MultipartFile> fileList = multiRequest.getFiles(name);
        				if(fileList!=null){
        					for(MultipartFile file:fileList){
        						if(file != null){
        							//取得当前上传文件的文件名称
        	    					String myFileName = file.getOriginalFilename();
        	    					myFileName=FtpUtil2.generateFileName(myFileName);
        	    					//如果名称不为"",说明该文件存在，否则说明该文件不存在
        	    					if(myFileName.trim() !=""){
        	    						myFileName=FtpUtil2.generateFileName(myFileName);
        	    						is = file.getInputStream();
        	    						FtpUtil2.upload(myFileName, is, ftpClient);
        	    						if("".equals(photoStr)){
        	    							photoStr+=ftp_photoDirectory+"/"+myFileName;
        	    						}else{
        	    							photoStr+=","+ftp_photoDirectory+"/"+myFileName;;
        	    						}
        	    					}
        						}
        					}
        				}
    				}
    			}
    			Users users = new Users();
    			users.setUserId(ud.getUserId());
    			users.setUserPhoto(photoStr);
				int num = userService.updateByPrimaryKeySelective(users );
    			map.put("photoStr", photoStr);
    			map.put("state", num);
    			map.put("msg", "上传成功");
    		}
		}catch(Exception e){
    		e.printStackTrace();
    		logger.error(e);
    		map.put("state", 0);
    		map.put("msg", "上传失败");
    	}finally {
    		try {
                if(ftpClient!=null){
                    FtpUtil2.closeConnection(ftpClient);
                }
            } catch (Exception e) {
                ftpClient=null;
            }
            try {
                if(is != null) {
                    is.close();
                }
            } catch (IOException e) {
                is=null;
            }
		}
		return map;
	}

	

	
	
	
}